package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.ecception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {


    private static SecretKey secretKey = Keys.hmacShaKeyFor("e2636077506729a8f61aff2441332e40e844a8ad44489efd80210ea6d1f51088".getBytes());

    /*
     *   username: 登录成功用户的账号
     *  userId: 登录用户的唯一标识
     *
     * compressWith(CompressionCodecs.GZIP):  对token数据进行压缩 ， 节省带宽
     *
     *
     *   eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAA_6tWKi5NUrJSKk9N0k1Myc3M0w3Jz07NU9JRSq0oULIyNDcyMTYwNzc20VEqLU4tykvMTQWqLsnPVYIIZKYAFdUCADKMjxtGAAAA.K7yYCvurX288E_yQNqaL2HFubzvtxUk5v0zEZWrKVRne8PFnmlzuC3XUrLVEPDIfhpf5iaK1IxIvb2MEEMrixw
     * */
    //创建Token
    public static String createToken(String username,Long userId){
        String token = Jwts.builder().setSubject("web-admin-Token")
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                .claim("username", username)
                .claim("userId", userId)
                .compressWith(CompressionCodecs.GZIP)
                .signWith(secretKey).compact();

        return token;
    }




    //解析Token
    public  static Claims parseToken(String token){
        Claims body = null;
        try {
            // 提供签名解析token
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);

            //获取token中的负载payload(数据)
            body = claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (Exception e) {
            throw new LeaseException("token验证失败",500);
        }

        return body;

    }



    public static void main(String[] args) {
        String token = createToken("tom", 1l);
        System.out.println(token);

        Claims claims = parseToken(token);

        System.out.println(claims.get("userId"));


    }
}
